<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
      <el-input v-model="data.name" prefix-icon="Search" style="width: 240px; margin-right: 10px" placeholder="请输入宠物用品名称"></el-input>
      <el-button type="info" plain @click="load">查询</el-button>
      <el-button type="warning" plain style="margin: 0 10px" @click="reset">重置</el-button>
    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-button type="primary" plain @click="handleAdd" v-if="data.user.role === 'PETSHOP'">新增</el-button>
      <el-button type="danger" plain @click="handleBatchDelete">批量删除</el-button>
    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-table tooltip-effect="dark myTooltip" stripe :data="data.tableData" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="name" label="宠物用品名称"></el-table-column>
        <el-table-column prop="shopName" label="店铺名称" v-if="data.user.role === 'ADMIN'"></el-table-column>
        <el-table-column prop="typeName" label="类型"></el-table-column>
        <el-table-column prop="descr" label="简介" show-overflow-tooltip></el-table-column>
        <el-table-column prop="image" label="图片">
          <template #default="scope">
            <el-image style="width: 50px; height: 50px; border-radius: 5px" :src="scope.row.image" :preview-src-list="[scope.row.image]" preview-teleported></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格"></el-table-column>
        <el-table-column prop="store" label="库存"></el-table-column>
        <el-table-column prop="sale" label="销量"></el-table-column>
        <el-table-column prop="status" label="销售状态">
          <template v-slot="scope">
            <el-tag type="success" v-if="scope.row.status === '上架'">上架</el-tag>
            <el-tag type="danger" v-if="scope.row.status === '下架'">下架</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template v-slot="scope">
            <el-button type="primary" circle :icon="Edit" @click="handleEdit(scope.row)" v-if="data.user.role === 'PETSHOP'"></el-button>
            <el-button type="danger" circle :icon="Delete" @click="handleDelete(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="card" v-if="data.total">
      <el-pagination
          @current-change="load"
          @size-change="handleSizeChange"
          background layout="total, prev, pager, next, jumper, sizes"
          :page-sizes="[1, 3, 5, 10, 15, 20, 30]"
          :page-size="data.pageSize"
          v-model:current-page="data.pageNum"
          :total="data.total"/>
    </div>

    <el-dialog title="宠物用品" v-model="data.formVisible" width="50%" destroy-on-close>
      <el-form ref="formRef" :rules="data.rules" :model="data.form" label-width="90px" style="padding: 20px">
        <el-form-item prop="typeId" label="用品类型">
          <el-select style="width: 100%" v-model="data.form.typeId">
            <el-option v-for="item in data.typeList" :key="item.id" :value="item.id" :label="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="name" label="用品名称">
          <el-input v-model="data.form.name" placeholder="请输入宠物用品名称"></el-input>
        </el-form-item>
        <el-form-item prop="descr" label="简介">
          <el-input v-model="data.form.descr" placeholder="请输入简介"></el-input>
        </el-form-item>
        <el-form-item prop="image" label="图片">
          <el-upload
              :action="baseUrl + '/files/upload'"
              :headers="{ 'token': data.user.token }"
              :on-success="handleFileUpload"
              list-type="picture"
          >
            <el-button type="primary">上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item prop="price" label="价格">
          <el-input-number :min="1" step="5" style="width: 200px" v-model="data.form.price" placeholder="请输入价格"></el-input-number>
        </el-form-item>
        <el-form-item prop="store" label="库存">
          <el-input-number :min="0" step="1" style="width: 200px" v-model="data.form.store" placeholder="请输入库存"></el-input-number>
        </el-form-item>
        <el-form-item prop="status" label="销售状态">
          <el-radio-group v-model="data.form.status">
            <el-radio-button label="上架" value="上架"></el-radio-button>
            <el-radio-button label="下架" value="下架"></el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog title="宠物详情" v-model="data.viewVisible" width="50%" :close-on-click-modal="false" destroy-on-close>
      <div class="editor-content-view" style="padding: 20px" v-html="data.content"></div>
      <template #footer>
    <span class="dialog-footer">
      <el-button @click="data.viewVisible = false">关 闭</el-button>
    </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import {reactive, ref, onBeforeUnmount, shallowRef} from 'vue'
  import request from '@/utils/request.js'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Delete, Edit} from '@element-plus/icons-vue'
  import '@wangeditor/editor/dist/css/style.css'

  const baseUrl = import.meta.env.VITE_BASE_URL

  const handleFileUpload = (res) => {
    data.form.image = res.data
  }

  const data = reactive({
    user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
    formVisible: false,
    form: {},
    tableData: [],
    pageNum: 1,
    pageSize: 10,
    total: 0,
    name: null,
    ids: [],
    shopList: [],
    typeList: [],
    rules: {
      typeId : [
        {required: true, message: '请选择宠物用品类型', trigger: 'change'}
      ],
      name: [
        {required: true, message: '请输入宠物用品名称', trigger: 'blur'}
      ],
      status: [
        {required: true, message: '请选择宠物销售状态', trigger: 'change'}
      ],
      price: [
        {required: true, message: '请输入宠物用品价格', trigger: 'blur'}
      ],
      store: [
        {required: true, message: '请输入宠物用品库存', trigger: 'blur'}
      ]
    },
    viewVisible: false,
    content: null
  })

  const formRef = ref()

  // 加载数据
  const load = () => {
    request.get('/goods/pageQuery', {
      params:{
        pageNum: data.pageNum,
        pageSize: data.pageSize,
        name: data.name
      }
    }).then(res => {
      if (res.code === '200') {
        data.tableData = res.data?.list || []
        data.total = res.data?.total
      } else {
        ElMessage.error(res.msg)
      }
    })
  }

  request.get('/goodsType/query/all').then(res => {
    if (res.code === '200') {
      data.typeList = res.data
    } else {
      ElMessage.error(res.msg)
    }
  })

  const handleAdd = () => {
    data.form = {status: '上架', price: 10, shopId: data.user.id}
    data.formVisible = true
  }

  const add = () => {
    request.post('/goods/add', data.form).then(res => {
      if (res.code === '200') {
        ElMessage.success('操作成功')
        data.formVisible = false
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }

  const save = () => {
    formRef.value.validate(validate => {
      if (validate) {
        if (!data.form.image) {
          ElMessage.warning('请上传图片')
          return
        }
        data.form.id ? update() : add()
      }
    })
  }

  const update = () => {
    request.put('/goods/update', data.form).then(res => {
      if (res.code === '200') {
        ElMessage.success('操作成功')
        data.formVisible = false
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }


  const reset = () => {
    data.name = null;
    load()
  }

  const handleDelete = (id) => {
    ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗？', '删除确认', { type: 'warning' }).then(res => {
      request.delete('/goods/delete/' + id).then(res => {
        if (res.code === '200') {
          ElMessage.success('删除成功')
          load()
        } else {
          ElMessage.error(res.msg)
        }
      })
    }).catch(err => {
      console.log(err)
    })
  }

  const handleEdit = (row) => {
    data.form = JSON.parse(JSON.stringify(row))
    data.formVisible = true
  }

  const handleSelectionChange = (rows) => {
    data.ids = rows.map(row => row.id)
  }

  const handleBatchDelete = () => {
    if (!data.ids.length) {
      ElMessage.warning('请选择数据')
      return
    }
    ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗？', '删除确认', { type: 'warning' }).then(res => {
      request.delete('/goods/delete/batch', {data: data.ids} ).then(res => {
        if (res.code === '200') {
          ElMessage.success('批量删除成功')
          load()
        } else {
          ElMessage.error(res.msg)
        }
      })
    })
  }

  const handleSizeChange = (newSize) => {
    data.pageSize = newSize
    data.pageNum = 1  // 切换页大小时重置到第一页
    load()
  }

  load()
</script>

<style>
.myTooltip {
  max-width: 40% !important;
}
</style>